package org.nfIt.controller;

import jakarta.validation.constraints.Pattern;
import org.hibernate.validator.constraints.URL;
import org.nfIt.entity.Result;
import org.nfIt.entity.User;
import org.nfIt.service.UserSerivce;
import org.nfIt.utils.JwtUtil;
import org.nfIt.utils.Md5Util;
import org.nfIt.utils.ThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * ClossName:UserController
 * Pakage:org.nfIt.controller
 * Description
 *
 * @Author L
 * @Create 2024/6/3 20:37
 * @Version 2023.1.3
 */
@RestController
//@Validated 和 @Pattern 相互搭配使用 正则
@Validated
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserSerivce userSerivce;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 用户注册
     * @param username 账号
     * @param password  密码
     */
    @PostMapping("/reg")
    public Result register(@Pattern(regexp = "^\\S{5,16}$") String username,@Pattern(regexp = "^\\S{5,16}$") String password) {
            //根据用户名查询用户
            User byUsername = userSerivce.findByUsername(username);
            //用户名为null,注册账号
            if (byUsername == null) {
                //注册账号
                userSerivce.regUserNameAndPassword(username, password);
                return Result.success();
            }
            //用户名不为null,用户名被占用
            return Result.error("用户名被占用");
    }

    /**
     *登入
     * # @Pattern (regexp = "^\\S{5,16}$") : 校验,相当于正则表达式
     * @param username 用户名
     * @param password 密码
     * @return
     */
    @PostMapping("/login")
    public Result login(@Pattern(regexp = "^\\S{5,16}$") String username,@Pattern(regexp = "^\\S{5,16}$") String password) {

        //根据用户名查询用户
        User loginUsername = userSerivce.findByUsername(username);

        if (loginUsername == null) {
            return Result.error("用户名错误");
        }

        //判断密码是否错误
        //Md5Util.getMD5String(password) ：加密密码, 与 数据库中已经加密的密码进行比对
        if (Md5Util.getMD5String(password).equals(loginUsername.getPassword())) {

            Map<String,Object> claims = new HashMap<>();
            claims.put("id",loginUsername.getId());
            claims.put("username",loginUsername.getUsername());
            //使用jwt封装数据
            String token = JwtUtil.genToken(claims);
            //把jwt令牌存储到redis
            ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
            //operations.set(key, value , 时间, 时间单位);
            operations.set(token,token,1, TimeUnit.HOURS);
            //返回token
            return Result.success(token);
        }
        return Result.error("密码错误");
    }


    /**
     * 根据用户名查询用户
     * @param token 使用@RequestHeader("Authorization")注解 获取 封装在请求头的token,
     *              token里封装了用户的 id 和 username
     *
     *登入时会获得一个jwt令牌
     * @return user
     */
    @GetMapping("/userinfo")
    public Result<User> userinfo(){

        //获取存入ThreadLocalUtil线程中的数据
        Map<String,Object> map = ThreadLocalUtil.get();
        //获取数据
        String username = (String) map.get("username");
        //根据用户名查询用户
        User user = userSerivce.findByUsername(username);
        return Result.success(user);
    }

    /**
     * 修改用户信息
     * @param user 对象
     * @return
     */
    @PutMapping("/update")
    public Result update(@RequestBody @Validated User user){

        userSerivce.update(user);
        System.out.println(user);
        return Result.success();

    }

    /**
     * 修改用户头像
     * @param avatarUrl 图片对应的url地址
     */
    @PatchMapping("/updateAvatar")
    public Result updateAvatar(@RequestParam @URL String avatarUrl){
        userSerivce.updateAvatar(avatarUrl);
        return Result.success();
    }

    /**
     *修改密码
     * @param params
     * @param token @RequestHeader("Authorization") ：从请求头中获取token,因为redis的中保存了token
     */
    @PatchMapping("/updatePwd")
    public Result updatePwd(@RequestBody Map<String,String> params,@RequestHeader("Authorization") String token){
        //检验参数
        //原密码
        String oldPwd = params.get("old_pwd");
        //新密码
        String newPwd = params.get("new_pwd");
        //确认的密码
        String rePwd = params.get("re_pwd");

        //检验参数不为null
        if (!StringUtils.hasLength(oldPwd) || !StringUtils.hasLength(newPwd) || !StringUtils.hasLength(rePwd)){
            return Result.error("缺少必要的参数！");
        }
        //从ThreadLocalUtil线程中获取username
        Map<String,Object> map = ThreadLocalUtil.get();
        String username = (String) map.get("username");
        User loginUser = userSerivce.findByUsername(username);

        if (!Md5Util.getMD5String(oldPwd).equals(loginUser.getPassword())){
            return Result.error("原密码错误");
        }
        if (!rePwd.equals(newPwd)){
            return Result.error("两次密码的填写不一致！");
        }
        //更新密码
        userSerivce.updatePwd(newPwd);

        //删除redis中对应的token
        ValueOperations<String, String> operations = stringRedisTemplate.opsForValue();
        operations.getOperations().delete(token);

        return Result.success();
    }


}
